package com.cdsf.kennedy.user;

import com.cdsf.common.conf.AbstractController;
import com.cdsf.common.exception.BusinessException;
import com.cdsf.common.util.BaseJson;
import com.cdsf.common.util.Page;
import com.cdsf.kennedy.user.domain.Role;
import com.cdsf.kennedy.user.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: kennedy
 * @Date: Created in 16:06 2018/2/7
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理")
public class RoleController extends AbstractController {
    @Autowired
    private RoleService roleService;

    @ApiOperation("新增角色")
    @PostMapping("/add")
    public BaseJson insert(Role role) {
        BaseJson baseJson = new BaseJson();
        // 判断是否重名
        Role query = new Role();
        query.setRoleName(role.getRoleName());
        Role exist = roleService.selectOne(query);
        assertNull(exist, "角色名已存在");
        try {
            roleService.insert(role);
            baseJson.setStatus(true);
        } catch (Exception e) {
            baseJson.setStatus(false);
            throw new BusinessException(e.getMessage());
        }
        return baseJson;
    }

    @ApiOperation("获取角色列表")
    @GetMapping("/getAll")
    public BaseJson getAll(Role role, Page page) {
        BaseJson baseJson = new BaseJson();
        List<Role> roles = roleService.getAll(role, page);
        baseJson.setStatus(true);
        baseJson.setData(roles);
        return baseJson;
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/delete/{uuid}")
    public BaseJson delete(@PathVariable("uuid") String uuid) {
        BaseJson baseJson = new BaseJson();
        roleService.delete(uuid);
        baseJson.setStatus(true);
        return baseJson;
    }

    @ApiOperation("获取角色信息")
    @GetMapping("/selectByPrimaryKey/{uuid}")
    public BaseJson selectByPrimaryKey(@PathVariable("uuid") String uuid) {
        BaseJson baseJson = new BaseJson();
        Role role = roleService.selectByPrimaryKey(uuid);
        baseJson.setStatus(true);
        baseJson.setData(role);
        return baseJson;
    }

    @ApiOperation("修改角色信息")
    @PutMapping("/updateByPrimaryKey")
    public BaseJson updateByPrimaryKey(Role role) {
        BaseJson baseJson = new BaseJson();
        Role query = new Role();
        query.setRoleName(role.getRoleName());
        Role exist = roleService.selectOne(query);
        if (exist != null && !exist.getUuid().equals(role.getUuid())) {
            throw new BusinessException("该角色名称已存在");
        }
        roleService.updateByPrimaryKey(role);
        baseJson.setStatus(true);
        return baseJson;
    }
}
